package com.atguigu.gulimall.cart.interceptor;

import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.constant.CartConstant;
import com.atguigu.common.vo.MemberResVo;
import com.atguigu.gulimall.cart.vo.UserInfoTo;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @Author 小坏
 * @Date 2021/1/28 14:20
 * @Version 1.0
 * @program: 父工程 gulimall 万物起源之地
 * <p>
 * SpringMVC 的 HandlerInterceptor
 * 在执行目标方法之前，判断用户的登录状态。并封装传递给Controller目标请求
 */


public class CartInterceptor implements HandlerInterceptor {

    /**
     * @program  ThreadLocal:线程共享数据这个数据
     *
     * 拦截器作用流程
     *
     */
    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    /**
     * 目标方法执行之前
     * 业务执行之前
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoTo infoTo = new UserInfoTo();
        HttpSession session = request.getSession(); //获取session
        MemberResVo memberresvo = (MemberResVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (memberresvo != null) {
            //用户登陆状态：存储用户ID
            infoTo.setUserId(memberresvo.getId());

        }

        //等于空的话从浏览器的cookie中获取uerKey
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if (name.equals(CartConstant.TEMP_USER_COOKIE_NAME)) {
                    infoTo.setUserKey(cookie.getValue());
                    infoTo.setTempUser(true); //相当于获取到了临时用户 就设置一个标识
                }
            }
        }

        //如果没有临时用户一定分配一个临时用户
        if (StringUtils.isEmpty(infoTo.getUserKey())) {
            String uuid = UUID.randomUUID().toString();
            infoTo.setUserKey(uuid);
        }


        //目标方法执行之前-------》再去目标方法中获取CartController
        threadLocal.set(infoTo);
        return true;
    }

    /**
     * 业务执行之后需要保存一个user-key(cookie)
     * 分配临时用户，让浏览器保存
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = threadLocal.get();

        /**
         * 1、有就用临时用户、就不放cookie了
         * 2、没有临时用户都会分配一个，响应浏览器
         * false
         */
        if (!userInfoTo.isTempUser()) {
            //响应cookie到浏览器
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIME); //设置cookie 30天过期
            response.addCookie(cookie);
        }


    }
}
